home *** CD-ROM | disk | FTP | other *** search
/ L' Effet Pommier 3 / L'Effet Pommier - Volume 03.iso / Programmation / Alpha ƒ / Help / Apple Events < prev    next >
Text File  |  1995-11-11  |  29KB  |  733 lines

  1.                 Apple Events
  2.  
  3. Alpha has very extensive support for scripting and inter-application 
  4. communication. 
  5.  
  6.     1) Alpha is completely scriptable in Tcl, which is far better suited for 
  7.        internal scripting than AppleScript.
  8.        
  9.     2) Alpha accepts the required apple events, plus 'dosc', which is used 
  10.        to tell Alpha to execute a Tcl script.
  11.        
  12.     3) Alpha has a command, AEBuild, which allows arbitrarily complicated 
  13.        apple events to be built and sent. 
  14.        
  15.     4) Queue'd replies of messages sent by AEBuild are AEPrint'd and passed 
  16.        to the tcl proc handleReply (in :Tcl:SystemCode:appleEvents.tcl).
  17.        
  18.     5) Alpha has several internal handlers to support interaction with 
  19.           Think, but basically the entire interface is done in Tcl using 
  20.           AEBuild. Compiler errors are parsed and passed to 
  21.           'handleThinkReply'.
  22.  
  23. ================================================================================
  24.  
  25. The following is a text version of the AEBuild/AEPrint docs. The 
  26. Word-formatted original is included in :Misc.
  27.  
  28. Apple Events    The « Builder/Printer
  29. Version 1.3.3
  30.  
  31. Jens Peter Alfke
  32. 11 October 1993
  33. AppleScript Team
  34. ⌐ Apple Computer, Inc. 1991╨1993
  35.  
  36. Introduction
  37. ------------
  38.  
  39. OK, What Is It?
  40.  
  41. Even with the helpful Object Support Library routines that assemble common 
  42. Apple event object descriptors, building descriptors and events is still a pain. I╒ve 
  43. written a library of two functions that make it quick and easy to build or display 
  44. Apple event descriptors and the Apple events themselves.
  45.  
  46. The AEBuild function takes a format string ╤ a description in a very simple 
  47. language of an Apple event descriptor ╤ and generates a real descriptor (which 
  48. could be a record or list or event) out of it. The AEPrint function does the reverse: 
  49. given an Apple event descriptor, list or record, it prettyprints it to a string. (The 
  50. resulting string, if sent to AEBuild, would reproduce the original AEDesc 
  51. structure.)
  52.  
  53. AEBuild can plug variable parameters into the structures it generates ╤ as with 
  54. printf, all you do is put marker characters in the format string and supply the 
  55. parameter values as extra function arguments.
  56.  
  57. The benefits of using this library are fourfold:
  58.  
  59.     Ñ    It╒s easier for you to write the code to build Apple event structures. You 
  60.         only have to remember one function call and a few simple syntax rules. 
  61.         Your resulting code is also easier to understand.
  62.  
  63.     Ñ    As of version 1.2, your code is even faster: AEBuild is three to four times 
  64.         as fast as the regular Apple Event Manager routines at constructing 
  65.         complex structures. (Your mileage may vary.)
  66.  
  67.     Ñ    Your code is smaller: the code for AEBuild and the AEStream library is 
  68.         about 6k in size, and the overhead for each call is minimal. (Most of the 
  69.         descriptor string consists of the same four-letter codes you╒d be using in 
  70.         your program code anyway, and the strings can even be stored in 
  71.         resources for more code savings.)
  72.         
  73.     Ñ    AEPrint helps in debugging programs, by turning mysterious AEDesc 
  74.         structures into human-readable text.
  75.  
  76. What╒s New?
  77.  
  78. In version 1.3:
  79.  
  80. Ñ    A new function, AEPrintSize, computes how long the string built by AEPrint 
  81.     would be, without actually creating it. This is useful if you want to allocate 
  82.     storage for the string dynamically.
  83.  
  84. Ñ    AEPrint no longer truncates hex dumps (of unknown descriptors) after 32 
  85.     bytes.
  86.  
  87. And in version 1.3.2:
  88.  
  89. Ñ    AEPrint no longer uses the stdio library. This should help reduce code size 
  90.     (and eliminate some problems in code resources) but to do it I had to cripple 
  91.     floating-point display. Floating-point descriptors now print as the integer part 
  92.     followed by ╥.XXXX╙.
  93.     
  94. And in version 1.3.3:
  95.  
  96. Ñ    After a brilliant suggestion by Rob Dye, AEPrint now uses the built in float-
  97.     to-text coercion to display floating-point descriptors.
  98.  
  99. Ñ    Fixed a possible problem with AEBuild input strings containing Return 
  100.     characters, in the MPW version of the library.
  101.  
  102. How To Call the Functions
  103. -------------------------
  104.  
  105. These are all C functions. They all take variable numbers of arguments, so they╒d 
  106. be difficult or impossible to call from Pascal, anyway. (And remember, kids: there 
  107. are no Pascal compilers for the PowerPC chip╔)
  108.  
  109. AEBuild
  110.  
  111. OSErr
  112.     AEBuild(  AEDesc *desc, const char *descriptorStr, ... ),
  113.     vAEBuild( AEDesc *desc, const char *descriptorStr, void *args );
  114.  
  115. AEBuild reads a null-terminated descriptor string (usually a constant, although it 
  116. could come from anywhere), parses it and builds a corresponding AEDesc 
  117. structure. (Don╒t worry, I╒ll describe the syntax of the descriptor string in the 
  118. next section.) If the descriptor string contains magic parameter-substitution 
  119. characters (╥@╙) then corresponding values of the correct type must be supplied 
  120. as function arguments, just as with printf.
  121.  
  122. (vAEBuild is analogous to vprintf: Instead of passing the parameters along with 
  123. the function, you supply a va_list, as defined in <stdarg.h>, that points to the 
  124. parameter list. It╒s otherwise identical.)
  125.  
  126. AEBuild returns an OSErr. Any errors returned by Apple Event Manager routines 
  127. while building the descriptor will be sent back to you. The most likely results are 
  128. memFullErr and errAECoercionFail. Also likely is aeBuildSyntaxErr, resulting 
  129. from an incorrect descriptor string. (Make sure to debug your descriptor strings, 
  130. perhaps using the demo application, before you put them in programs!)
  131. The basic version of AEBuild just reports that a syntax error occurred, without 
  132. giving any additional information. If you want to know more (perhaps the string 
  133. came from a user, to whom you╒d like to report a helpful error message) you can 
  134. use the other version of the library. This version includes a wee bit of extra code, 
  135. and two global variables that will contain useful information after a syntax error:
  136.  
  137. extern AEBuild_SyntaxErrType
  138.     AEBuild_ErrCode;
  139. extern long
  140.     AEBuild_ErrPos;
  141.  
  142. AEBuild_ErrCode is an enumerated value that will contain a specific error code. 
  143. The error codes are defined in AEBuild.h. AEBuild_ErrPos will contain the index 
  144. into the descriptor string at which the error occurred: usually one character past 
  145. the end of the offending token.
  146. AEBuildParameters
  147.  
  148. AEBuildParameters
  149.  
  150. OSErr    AEBuildParameters(  AppleEvent *event, const char *descriptorStr, ... );
  151.  
  152. AEBuildParameters adds parameters and/or attributes to an existing Apple 
  153. event. descriptorStr specifies the parameters (required and optional) and 
  154. attributes. Its syntax is described below (see especially the Apple Event 
  155. Descriptor Strings subsection); it╒s almost the same as the syntax for AEBuild, 
  156. with a few additions and modifications.
  157.  
  158. (vAEBuildParameters is analogous to vprintf: Instead of passing the parameters 
  159. along with the function, you supply a va_list, as defined in <stdarg.h>, that 
  160. points to the parameter list. It╒s otherwise identical.)
  161.  
  162. AEBuildAppleEvent
  163.  
  164. AEBuildAppleEvent(    AEEventClass theClass, AEEventID theID,
  165.                     DescType addressType, void *addressData, long addressLength,
  166.                     short returnID, long transactionID,
  167.                     AppleEvent *event,
  168.                     const char *descriptorStr, ... );
  169.  
  170. AEBuildAppleEvent is like AEBuild but builds an Apple event, including 
  171. parameters and attributes. Or, you could say that it╒s like AEBuildParameters but 
  172. creates the event from scratch.
  173.  
  174. Most of the parameters are just like the parameters to AECreateAppleEvent, 
  175. although you pass the target address data directly, instead of via a pre-built 
  176. descriptor. The resulting Apple event will appear in the event parameter.
  177. descriptorStr specifies the parameters (required and optional) and attributes. 
  178. The syntax is described below (see especially the Apple Event Descriptor Strings 
  179. subsection); it╒s almost the same as the syntax for AEBuild, with a few additions 
  180. and modifications.
  181.  
  182. (vAEBuildAppleEvent is analogous to vprintf: Instead of passing the parameters 
  183. along with the function, you supply a va_list, as defined in <stdarg.h>, that 
  184. points to the parameter list. It╒s otherwise identical.)
  185.  
  186. AEPrint
  187.  
  188. OSErr AEPrint( AEDesc *desc, char *bufStr, long bufSize );
  189.  
  190. AEPrint reads the Apple event descriptor desc and writes a corresponding 
  191. descriptor string into the string pointed to by bufStr. It will write no more than 
  192. bufSize characters, including the trailing null character. Any errors returned by 
  193. Apple Event Manager routines will be returned to the caller; this isn╒t very likely 
  194. unless the AEDesc structure is somehow corrupt.
  195.  
  196. The descriptor string produced, if sent to AEBuild, will build a descriptor 
  197. identical to the original one. AEPrint tries to detect AERecords that have been 
  198. coerced to other types and print them as coerced records. Structures of unknown 
  199. type that can╒t be coerced to AERecords are dumped as hex data.
  200.  
  201. AEPrint can also print complete Apple events as well as regular descriptors. The 
  202. syntax of the resulting string for an event is like that used by AEBuildParameters 
  203. and AEBuildAppleEvent, except that:
  204.  
  205. Ñ    The string begins with the event class and ID separated by a backslash.
  206. Ñ    the parameter list is surrounded by curly braces.
  207. Ñ    Attributes are also displayed; they look like parameters but are preceded by 
  208.     ╥&╙s.
  209.  
  210.      The builder functions do not accept this event syntax yet.╩╩
  211.  
  212. AEPrintSize
  213.  
  214. OSErr AEPrintSize( AEDesc *desc, long *bufSizeNeeded );
  215.  
  216. AEPrintSize computes the buffer size that AEPrint would require if given the 
  217. same descriptor. (The size is equal to the string length, plus 1 byte for the trailing 
  218. null.) This is handy for pre-flighting AEPrint, if you want to allocate the buffer 
  219. dynamically  instead of relying on one of fixed size .
  220.  
  221. Descriptor-String Syntax
  222. ------------------------
  223.  
  224. The real meat of all this, of course, is the syntax of the descriptor strings. It╒s 
  225. pretty simple: basic data types like numbers and strings can be described 
  226. directly, and then built up into lists and records. I╒ve even provided a pseudo-
  227. BNF grammar (next section) for those of you who actually enjoy reading those things.
  228.  
  229. Basic Types
  230.  
  231. The fundamental data types are:
  232.  
  233. Type            Examples        Type-code       Description
  234. ----            --------        ---------       -----------
  235. Integer         1234            'long' or       A sequence of decimal digits,
  236.                 -5678           'shor'          optionally preceded by a minus
  237.                                                 sign.
  238.  
  239. Enum/Type       whos            'enum'          A magic four-letter code. Will be
  240. Code            longint         (Use coercion   truncated or padded with spaces
  241.                 'long'          to change to    to exactly four characters. If you
  242.                 <=              'type')         put straight or curly single-
  243.                 '8-)'                           quotes around it, it can contain
  244.                 ╘ZQ 5╒                          any characters. If not, it can╒t
  245.                 m                               contain any of: @╘'╥╙:-,([{}])
  246.                                                 and can╒t begin with a digit.
  247.  
  248. String      ╥A String.╙         'TEXT'          Any sequence of characters
  249.             ╥Multiple lines                     within open and close curly
  250.             are okay.╙                          quotes. Won╒t be null-terminated.
  251.  
  252. Hex Data    ╟4170706C65╚        ??              An even number of hex digits
  253.             ╟0102 03ff          (Must be        between French quotes (Option-
  254.              e b 6 c╚           coerced to      \, Option-Shift-\). Whitespace is
  255.                                 some type)      ignored.
  256.  
  257.  Yes, you have to use the actual four-letter codes for enums, type codes, keywords 
  258. and object types, instead of the mnemonic constants.  Luckily the codes are 
  259. semi-mnemonic anyway.  I did it this way to avoid the massive overhead, both in code 
  260. size and execution speed, of a symbol table.  You can find the definitions of the 
  261. constants in the text file ╥AEObjects.p╙, which is part of the Apple Events Object 
  262. Support Library.╩╩
  263.  
  264. Coercion
  265.  
  266. Any basic element (except a hex string) by itself is a descriptor, whose 
  267. descriptorType is as given in the table. You can coerce a basic element to a 
  268. different type by putting it in parentheses with a type-code placed before it. Here 
  269. are some examples:
  270.  
  271.     sing(1234)
  272.     type(line)
  273.     long(CODE)
  274.     hexd(╥A String╙)
  275.     'blob'(╟4170706C65╚)
  276.  
  277.     Coercions of numeric values are effected by calling AECoerceDesc; if the 
  278. coercion fails, you╒ll get an errAECoercionFail error returned to you. 
  279. Coercions of other types just replace the descriptorType field of the AEDesc.╩╩
  280.  
  281.     Hex strings must be coerced to something, since they have no intrinsic type.╩╩
  282.  
  283. You can also coerce nothing, to get a descriptor with zero-length data:
  284.  
  285.     emty()
  286.  
  287. Even the type can be omitted, leaving just (), in which case the type is 'null'.
  288.  
  289. Lists
  290.  
  291. To make an AEDescList, just enclose a comma-separated list of descriptors in 
  292. square brackets. For example:
  293.  
  294.     [123, -456, ╥et cetera╙]
  295.     [sing(1234), long(CODE),
  296.      [╥wheels╙, ╥within wheels╙]]
  297.     []
  298.  
  299. The elements of a list can be of different types, and a list can contain other lists or 
  300. records (see below) as elements.
  301.  
  302. Lists cannot be coerced to other types; the type of a list is always 'list'.
  303.  
  304. Records
  305.  
  306. An AERecord is indicated by a comma-separated list of elements enclosed in curly 
  307. braces. Each element of a record consists of a keyword (a type-code, as described 
  308. under Basic Types) followed by a ╥:╙, followed by a value, which can be any 
  309. descriptor: a basic type, a list or another record. For example:
  310.  
  311.     {x:100, y:-100}
  312.     {'origin': {x:100, y:-100}, extent: {x:500, y:500},
  313.      cont: [1, 5, 25]}
  314.     {}
  315.  
  316. The default type of a record is 'reco'.  Many of the Apple Events Object 
  317. Model structures are AERecords that have been coerced to some other data 
  318. type, like 'indx' or 'whos'.  You can coerce a record structure to any 
  319. type by preceding it with a type code.  For example:
  320.  
  321.     rang{ star: 5, stop: 6}
  322.  
  323. s Warning Coercing to an existing type, such as 'bool' or 'TEXT', is a 
  324. bad idea.  Anyone parsing the descriptor (including AEPrint) will 
  325. recognize the type and assume that the data has the normal 
  326. interpretation, which in this case it wouldn╒t.  Bad to awful things 
  327. would happen.  Don╒t do it.
  328.  
  329. Apple Events
  330.  
  331. The syntax of the formatting string for an entire Apple event (as passed to 
  332. AEBuildAppleEvent) is almost identical to that of a record. Each keyed element 
  333. specified in the string becomes a parameter or attribute of the event. The 
  334. differences are:
  335.  
  336. Ñ    There are no curly-braces at the beginning and end of the string.
  337. Ñ    The character ╥~╙ before a parameter keyword makes it optional.
  338.  
  339. Here╒s an example of how to construct an Open Selection event for the Finder:
  340.  
  341.     AliasHandle parent, itemToOpen;
  342.     const OSType finderSignature = 'MACS';
  343.     AppleEvent event;
  344.     OSErr err;
  345.  
  346.     // Construct the aliases here (not shown)
  347.  
  348.     err= AEBuildEppleEvent(
  349.             'FNDR', 'SOPE',
  350.             typeApplSignature, @finderSignature, sizeof(finderSignature),
  351.             kAutoGenerateReturnID, kAnyTransactionID,
  352.             &event,                                        // Event to be created
  353.             "----: alis(@@), fsel: [alis(@@)]",            // Format string
  354.                 parent,                                    // param for 1st @@
  355.                 itemToOpen                                // param for 2nd @@
  356.     );
  357.     
  358. Substituting Parameters
  359.  
  360. To plug your own values into the midst of a descriptor, use the magic ╥@╙ 
  361. character. You can use ╥@╙ anywhere you can put a basic element like an integer. 
  362. Each ╥@╙ is replaced by a value taken from the parameter list sent to the AEBuild 
  363. function. The type of value created depends on the context in which the ╥@╙ is 
  364. used: in particular, how it╒s coerced.
  365.  
  366. Type Coerced to:    Type of fn parameter read:            Comments:
  367. ----------------    --------------------------            ---------
  368. No coercion            AEDesc*                                A plain ╥@╙ will be replaced with a
  369.                                                         descriptor parameter.
  370.                                                         
  371. Numeric             (bool, shor,
  372.                     long, sing, doub, exte)    short, short, long, float,
  373.                     short double, double                Remember that THINK C╒s double
  374.                                                         corresponds to type 'exte'!
  375.                                                         
  376. TEXT                char*                                Pointer to a null-terminated C string.
  377.  
  378. Any other type        long followed by void*                Expects a length parameter followed by
  379.                                                         a pointer to the descriptor data.
  380.                                                         
  381. s    Important    Note particularly: that TEXT parameters must be null-terminated 
  382. strings, although the resulting descriptor data will not be null-
  383. terminated; and that the general case expects two parameters: the 
  384. data╒s size and location. ╩╩s
  385.  
  386. In addition, you can substitute data from a handle by using two @ signs. An ╥@@╙ 
  387. parameter will read a single handle from the parameter list and use the data 
  388. pointed to by that handle as the value of the descriptor. The ╥@@╙ must be 
  389. coerced so that AEBuild will know what type to make the descriptor; however, 
  390. the type coerced to can be anything (the table above is ignored.)
  391.  
  392. This mechanism is still a bit limited, and may well be improved in the future.
  393.  
  394. Descriptor-String Grammar
  395. -------------------------
  396.  
  397. Since no language, however small, can be taken seriously unless it comes fully 
  398. equipped with a formidable-looking BNF grammar specification, I here present 
  399. one. No attempt has been made to prevent Messrs. Backus and/or Naur from 
  400. rolling over in their respective graves.
  401.  
  402. Character Classification:
  403.  
  404. whitespace    ╘ ╒, ╘\r╒, ╘\n╒, ╘\t╒
  405. digit    0 ╔ 9
  406. paren, bracket,
  407. braces    (, ), [, ], {, }
  408. single-quote    '
  409. double quotes    ╥, ╙
  410. hex quotes    ╟, ╚
  411. colon    :
  412. comma    ,
  413. at-sign    @
  414. identchar    any other printable character
  415.  
  416. Tokens:
  417.  
  418. ident ::=    identchar (identchar | digit)*    ╤Padded/truncated
  419.     ' character* '    to exactly 4 chars
  420. integer ::=    [ - ] digit+    ╤Just as in C
  421. string ::=    ╥ (character)* ╙
  422. hexstring ::=    ╟ (hexdigit | whitespace)* ╚    ╤Even no. of digits, please
  423.  
  424. Grammar Rules for AEBuild:
  425.  
  426. formatstring ::=    obj    ╤This is the top level of syntax
  427. obj ::=    data    ╤Single AEDesc; shortcut for (data)
  428.     structure    ╤Un-coerced structure
  429.     ident structure    ╤Coerced to some other type
  430. structure ::=    ( data )    ╤Single AEDesc
  431.     [ objectlist ]    ╤AEList type
  432.     { keywordlist }    ╤AERecord type
  433. objectlist ::=    ╟blank╚    ╤Comma-separated list of things
  434.     obj [ , obj ]*
  435. keywordpair ::=    ident : obj    ╤Keyword/value pair
  436. keywordlist ::=    ╟blank╚    ╤List of said pairs
  437.     keywordpair [ , keywordpair ]*
  438. data ::=    @    ╤Gets appropriate data from fn param
  439.     integer    ╤'shor' or 'long' unless coerced
  440.     ident    ╤A 4-char type code ('type') unless coerced
  441.     string    ╤Unterminated text; 'TEXT' type unless coerced
  442.     hexstring    ╤Raw hex data; must be coerced to some type!
  443.     
  444. Grammar Rules for AEBuildAppleEvent:
  445.  
  446. eventstring ::=    evtkeywordlist    ╤Top level syntax for AEBuildAppleEvent
  447. evtkeywordpair ::=    [~] ident : obj    ╤Keyword/value pair
  448. evtkeywordlist ::=    ╟blank╚    ╤List of said pairs
  449.     evtkeywordpair [ , evtkeywordpair ]*
  450.     
  451. There. Now it╒s all crystal-clear, right?
  452.  
  453. An Example & Timing Comparison
  454. ------------------------------
  455.  
  456. As an example, I╒ll take a C function to generate an object descriptor (taken from 
  457. a Pascal example in the Object Model ERS, fleshed out and with gobs of error 
  458. checking added) and turn it into a call to AEBuild. The object descriptor we want 
  459. to generate is:
  460.  
  461. First line of document 'Spinnaker' whose first word is 'April'
  462. and whose second word is 'is'
  463.  
  464. Then I╒ll execute both functions and compare their execution times.
  465.  
  466. C Code Using Object-Packing Library
  467.  
  468. OSErr
  469. BuildByHand( AEDesc *dDocument, AEDesc *theResultObj )
  470. {
  471.     OSErr err;
  472.     AEDesc dObjectExamined, dNum, dWord1, dWord2, dAprilText, dIsText,
  473.            dComparison1, dComparison2, dLogicalTerms, dTheTest, dLineOne, dTestedLines;
  474.     
  475.     dObjectExamined.dataHandle =    /* Zero things to start out with so we can safely */
  476.         dNum.dataHandle =                /* execute our fail code if things don't work out */
  477.         dWord1.dataHandle =
  478.         dWord2.dataHandle =
  479.         dAprilText.dataHandle =
  480.         dIsText.dataHandle =
  481.         dComparison1.dataHandle =
  482.         dComparison2.dataHandle =
  483.         dLogicalTerms.dataHandle =
  484.         dTheTest.dataHandle =
  485.         dLineOne.dataHandle =
  486.         dTestedLines.dataHandle =
  487.             NIL;
  488.  
  489.     if( err= AECreateDesc( 'exmn', NIL, 0, &dObjectExamined ) )
  490.         goto fail;
  491.  
  492.     if( err= MakeIndexDescriptor(1,&dNum) )
  493.         goto fail;
  494.     if( err= MakeObjDescriptor( 'word', &dObjectExamined, formIndex, &dNum,
  495.                     false, &dWord1) )
  496.         goto fail;
  497.     if( err= AECreateDesc( 'TEXT', "April", 5, &dAprilText ) )
  498.         goto fail;
  499.  
  500.     AEDisposeDesc(&dNum);
  501.     if( err= MakeIndexDescriptor(2,&dNum) )
  502.         goto fail;
  503.     if( err= MakeObjDescriptor( 'word', &dObjectExamined, formIndex, &dNum,
  504.                     true, &dWord2) )
  505.         goto fail;
  506.     if( err= AECreateDesc( 'TEXT', "is", 2, &dIsText ) )
  507.         goto fail;
  508.  
  509.     if( err= MakeCompDescriptor( '=   ', &dAprilText, &dWord1, true, &dComparison1 ) )
  510.         goto fail;
  511.     if( err= MakeCompDescriptor( '=   ', &dIsText,      &dWord2, true, &dComparison2 ) )
  512.         goto fail;
  513.  
  514.     if( err= AECreateList( NIL, 0, false, &dLogicalTerms ) )
  515.         goto fail;
  516.     if( err= AEPutDesc( dLogicalTerms, 1, dComparison1 ) )
  517.         goto fail;
  518.     if( err= AEPutDesc( dLogicalTerms, 2, dComparison2 ) )
  519.         goto fail;
  520.         
  521.     AEDisposeDesc(&dComparison1);
  522.     AEDisposeDesc(&dComparison2);
  523.     
  524.     if( err= MakeLogicalDescriptor( &dLogicalTerms, 'AND ', true, &dTheTest) )
  525.         goto fail;
  526.     
  527.     if( err= MakeObjDescriptor(classLine,&dDocument,formTest,&dTheTest,true,
  528.                                     &dTestedLines) )
  529.         goto fail;
  530.  
  531.     if( err= MakeIndexDescriptor(1,&dLineOne) )
  532.         goto fail;
  533.     if( err= MakeObjDescriptor( classLine, &dTestedLines, formIndex, &dLineOne,
  534.             true, theResultObj ) )
  535.         goto fail;
  536.     return noErr;
  537.     
  538. fail:                                            /* Clean up in case we couldn't build it */
  539.     AEDisposeDesc(theResultObj);
  540.     AEDisposeDesc(&dObjectExamined);
  541.     AEDisposeDesc(&dNum);
  542.     AEDisposeDesc(&dWord1);
  543.     AEDisposeDesc(&dWord2);
  544.     AEDisposeDesc(&dAprilText);
  545.     AEDisposeDesc(&dIsText);
  546.     AEDisposeDesc(&dComparison1);
  547.     AEDisposeDesc(&dComparison2);
  548.     AEDisposeDesc(&dLogicalTerms);
  549.     AEDisposeDesc(&dTheTest);
  550.     AEDisposeDesc(&dLineOne);
  551.     AEDisposeDesc(&dTestedLines);
  552.     
  553.     return err;
  554. }
  555.  
  556. MPW 3.2b5 C compiled this into 816 bytes of object code.
  557. I found that the average time to execute this function was 0.0188 seconds 
  558. (Quadra 700) or 0.0113 seconds (IIfx).á Use this figure for comparison only; your 
  559. times may vary. The timing is especially dependent on the number of blocks in 
  560. the heap, since so many block allocations and disposals are happening.
  561.  
  562. AppleScript
  563.  
  564. First line of document 'Spinnaker' whose first word is 'April'
  565. and whose second word is 'is'
  566.  
  567. Descriptor String
  568.  
  569. obj{ want:type('line'),
  570.      from: obj{ want: type('line'), from: @, form: 'test',
  571.                 seld: logi{
  572.                            term: [comp{ relo:=, obj1:╥April╙,
  573.                                         obj2:obj{ want:type('word'), from:exmn(), 
  574.                                                   form:indx, seld:1 }
  575.                                       },
  576.                                   comp{ relo:=, obj1:╥is╙,
  577.                                         obj2:obj{ want:type('word'), from:exmn(),
  578.                                                   form:indx, seld:2 }
  579.                                       }
  580.                                  ],
  581.                            logc:AND
  582.                          }
  583.               },
  584.      form: 'indx',
  585.      seld: 1
  586. }
  587.  
  588. AEBuild Call
  589.  
  590. char descriptor[] =                /* Same descriptor string as above. Note clever */
  591. "obj{ want:type('line'),"        /* method used to break string across lines. */
  592.     "from: obj{ want: type('line'), from: @, form: 'test',"        /* Note parameter here */
  593.                "seld: logi{"
  594.                           "term: [comp{ relo:=, obj1:╥April╙,"
  595.                                        "obj2:"
  596.                              "obj{ want:type('word'), from:exmn(), form:indx, seld:1 }},"
  597.                                  "comp{ relo:=, obj1:╥is╙,"
  598.                                        "obj2:"
  599.                              "obj{ want:type('word'), from:exmn(), form:indx, seld:2 }}"
  600.                                 "],"
  601.                           "logc:AND"
  602.                         "}"
  603.              "},"
  604.     "form: 'indx',"
  605.     "seld: 1"
  606. "}";
  607.  
  608. void PackWordDesc( AEDesc *dDocumentObject )    /* ╥Spinnaker╙ descriptor is a parameter */
  609. {
  610.     err = AEBuild(&theResultObj,
  611.                     descriptorString,
  612.                     dDocumentObject);                    /* AEDesc* parameter for "@" */
  613. }
  614.  
  615. MPW 3.2b5 C compiled this into 42 bytes of object code, plus 310 bytes of data 
  616. storage for the string.
  617.  
  618. I found that the average time to execute this function was 0.0049 seconds 
  619. (Quadra 700) or 0.0070 seconds (IIfx). Use this figure for comparison only; your 
  620. times may vary. The timing is dependent on the number of blocks in the heap, 
  621. since heap blocks are being allocated and resized.
  622.  
  623. Timing Conclusions
  624.  
  625. With previous versions of this library, there was a 70% increase in execution time 
  626. when using the AEBuild routine. After delivering the bad news, I wrote:
  627. However, if speed does become an issue, there is always the option of 
  628. turbocharging AEBuild by having it directly build descriptors without going 
  629. through the Apple Event Manager functions at all. This would save an incredible 
  630. number of Memory Manager calls and probably increase performance 
  631. severalfold. Anyone using AEBuild will get all these improvements for free.
  632. This is exactly what I did in version 1.1. In fact, I wrote a library (AEStream) to 
  633. do it, so you can do it too. It╒s easy.
  634. AEBuild is now 1.5 to 4 times as fast (depending on CPU) as the using the Apple 
  635. Event Manager and/or Object Packing Library routines. (This means that 
  636. AEStream was responsible for a threefold speed-up in AEBuild. Not bad, when 
  637. you take into account other overhead like parsing the format string!)
  638. Needless to say, if you were already using AEBuild you get this speed increase 
  639. absolutely free. Enjoy!
  640.  
  641. The Demo Program
  642. ----------------
  643.  
  644. I╒ve included a demonstration program in the distribution. This is a program I 
  645. used to debug the library. It reads a line of input, uses AEBuild to translate it into 
  646. an AEDesc, uses AEPrint to translate the AEDesc back into a string, and prints 
  647. each resulting string. Error codes are reported, including syntax-error messages. 
  648. The source code is provided in case you want to see how the functions are called.
  649. s    Warning    The demo tool does not handle parameter substitution (the ╥@╙ 
  650. character). If you try to substitute parameters, messy and 
  651. unpleasant things may happen. Use some numeric value in place 
  652. of parameters, and then replace it with ╥@╙s after you paste the 
  653. string into your program.
  654.  
  655. The Header Files
  656.  
  657. Here for your convenience are printouts of the header files as of 21 July 1992.
  658.  
  659. AEBuild.h
  660.  
  661. #define aeBuild_SyntaxErr    12345            /* Let's get an Official OSErr code someday */
  662.  
  663. typedef enum{                                /* Syntax Error Codes: */
  664.     aeBuildSyntaxNoErr = 0,                        /* (No error) */
  665.     aeBuildSyntaxBadToken,                        /* Illegal character */
  666.     aeBuildSyntaxBadEOF,                            /* Unexpected end of format string */
  667.     aeBuildSyntaxNoEOF,                            /* Unexpected extra stuff past end */
  668.     aeBuildSyntaxBadNegative,                    /* "-" not followed by digits */
  669.     aeBuildSyntaxMissingQuote,                    /* Missing close "'" */
  670.     aeBuildSyntaxBadHex,                            /* Non-digit in hex string */
  671.     aeBuildSyntaxOddHex,                            /* Odd # of hex digits */
  672.     aeBuildSyntaxNoCloseHex,                        /* Missing "╚" */
  673.     aeBuildSyntaxUncoercedHex,                    /* Hex string must be coerced to a type */
  674.     aeBuildSyntaxNoCloseString,                    /* Missing "╙" */
  675.     aeBuildSyntaxBadDesc,                        /* Illegal descriptor */
  676.     aeBuildSyntaxBadData,                        /* Bad data value inside (╔) */
  677.     aeBuildSyntaxNoCloseParen,                    /* Missing ")" after data value */
  678.     aeBuildSyntaxNoCloseBracket,                /* Expected "," or "]" */
  679.     aeBuildSyntaxNoCloseBrace,                    /* Expected "," or "}" */
  680.     aeBuildSyntaxNoKey,                            /* Missing keyword in record */
  681.     aeBuildSyntaxNoColon,                        /* Missing ":" after keyword in record */
  682.     aeBuildSyntaxCoercedList,                    /* Cannot coerce a list */
  683.     aeBuildSyntaxUncoercedDoubleAt                /* "@@" substitution must be coerced */
  684. } AEBuild_SyntaxErrType;
  685.  
  686. // In all the "v..." functions, the "args" parameter is really a va_list.
  687. // It's listed as void* here to avoid having to #include stdarg.h.
  688.  
  689. // Building a descriptor:
  690.  
  691. OSErr
  692.     AEBuild(  AEDesc *dst, const char *src, ... ),
  693.     vAEBuild( AEDesc *dst, const char *src, const void *args );
  694.  
  695. // Adding a parameter to an Apple event:
  696.  
  697. OSErr
  698.     AEBuildParameters( AppleEvent *event, const char *format, ... ),
  699.     vAEBuildParameters( AppleEvent *event, const char *format, const void *args );
  700.  
  701. // Building an entire Apple event:
  702.  
  703. OSErr
  704.     AEBuildAppleEvent( AEEventClass theClass, AEEventID theID,
  705.                         DescType addressType, const void *addressData, long addressLength,
  706.                         short returnID, long transactionID, AppleEvent *result,
  707.                         const char *paramsFmt, ... ),
  708.     vAEBuildAppleEvent( AEEventClass theClass, AEEventID theID,
  709.                         DescType addressType, const void *addressData, long addressLength,
  710.                         short returnID, long transactionID, AppleEvent *resultEvt,
  711.                         const char *paramsFmt, const void *args );
  712. AEBuildGlobals.h
  713. /*
  714.  *    AEBuildGlobals.h                            Copyright ⌐1991 Apple Computer, Inc.
  715.  */
  716.  
  717.  
  718. extern AEBuild_SyntaxErrType
  719.     AEBuild_ErrCode;                    /* Examine after AEBuild returns a syntax error */
  720. extern long
  721.     AEBuild_ErrPos;                    /* Index of error in format string */
  722. AEPrint.h
  723. /*
  724.  *    AEPrint.h                                        Copyright ⌐1991 Apple Computer, Inc.
  725.  */
  726.  
  727. OSErr AEPrint( AEDesc *desc, char *bufStr, long bufSize );
  728.  
  729.  
  730. á Yes, it really took half again as long on a Quadra! I think that cache flushing during the PACK 
  731. call is responsible. (It barely slows down at all when you disable the caches.)
  732.  
  733.